package com.icss.id.service.Impl;

import com.icss.id.dao.IRecordDao;
import com.icss.id.dao.ItemsDao;
import com.icss.id.dao.UserDao;
import com.icss.id.pojo.Item;
import com.icss.id.pojo.Record;
import com.icss.id.pojo.User;
import com.icss.id.service.IRecordService;
import javassist.runtime.Desc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class IRecordServiceImpl implements IRecordService {

    @Autowired
    private IRecordDao iRecordDao;
    @Autowired
    private ItemsDao itemsDao;
    @Autowired
    private UserDao userDao;

    /**
     * 查询违法记录并分页
     *
     * @param pageNum
     * @return
     */
    public Page<Record> findRecordPage(Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        Specification<Record> specification = new Specification<Record>() {

            @Override
            public Predicate toPredicate(Root<Record> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                Root<Item> item = criteriaQuery.from(Item.class);
                Root<User> user = criteriaQuery.from(User.class);
                Join<Item, Record> join = root.join("item", JoinType.INNER);
                Join<User, Record> join1 = root.join("user", JoinType.INNER);

                predicates.add(criteriaBuilder.equal(root.get("item"), item.get("itemId")));
                predicates.add(criteriaBuilder.equal(root.get("user"), user.get("userId")));


                criteriaQuery.distinct(true);
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.ASC, "recordId");
        PageRequest pageable = PageRequest.of(pageNum - 1, 5,sort);

        Page<Record> all = iRecordDao.findAll(specification, pageable);

        return all;

    }

    /**
     * 根据车牌号模糊查询 。时间段查询 并分页
     *
     * @param carNum
     * @param start
     * @param end
     * @param pageNum
     * @return
     */
    public Page<Record> findRecordByCarNum(String carNum, Timestamp start, Timestamp end, Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        Specification<Record> specification = new Specification<Record>() {

            @Override
            public Predicate toPredicate(Root<Record> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                Root<Item> item = criteriaQuery.from(Item.class);
                Root<User> user = criteriaQuery.from(User.class);
                Join<Item, Record> join = root.join("item", JoinType.INNER);
                Join<User, Record> join1 = root.join("user", JoinType.INNER);

                predicates.add(criteriaBuilder.equal(root.get("item"), item.get("itemId")));
                predicates.add(criteriaBuilder.equal(root.get("user"), user.get("userId")));
                if (carNum != null && start != null && end != null) {
                    predicates.add(criteriaBuilder.greaterThan(root.get("itemDate"), start));
                    predicates.add(criteriaBuilder.lessThan(root.get("itemDate"), end));
                }

                predicates.add(criteriaBuilder.like(user.get("carNum").as(String.class), "%" + carNum + "%"));

                criteriaQuery.distinct(true);
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        PageRequest pageable = PageRequest.of(pageNum - 1, 5);

        Page<Record> time = iRecordDao.findAll(specification, pageable);

        return time;
    }

    /**
     * 添加违法记录
     * @param username
     * @param itemId
     * @param address
     */
    public void updateRecord(String username, Integer itemId, String address, String itemDate) {
        Record record = new Record();
        User user = userDao.findByUserName(username);
        Item item = itemsDao.findByItemId(itemId);

        user.setUnDoViolationCount(user.getUnDoViolationCount()+1);
        user.setViolationCount(user.getViolationCount()+1);

        if (user.getAvailableScore()-item.getR_score()<0){
            user.setAvailableScore(0);
        }else{
            user.setAvailableScore(user.getAvailableScore()-item.getR_score());
        }
        item.setViolationNum(item.getViolationNum()+1);
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = s.parse(itemDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Timestamp timestamp = new Timestamp(date.getTime());

        record.setItemDate(timestamp);
        record.setAddress(address);
        record.setStatus(false);
        record.setUser(user);
        record.setItem(item);
        iRecordDao.save(record);

    }
}
